import { env } from "~/env";

import { type Message } from "../messaging";
import { fetchStream } from "../sse";

import { type TeamMember, type ChatEvent, SessionHistoryResponse, SessionListItem } from "./types";
import { useStore } from "../store/store";

export function chatStream(
  userMessage: Message,
  state: { messages: { role: string; content: string }[] },
  params: {
    deepThinkingMode: boolean;
    searchBeforePlanning: boolean;
    teamMembers: string[];
    sessionId?: string | null;  // 修改类型为string | null
    username?: string | null;
    mode?: "search" | "chat"; // 添加聊天模式参数
  },
  options: { abortSignal?: AbortSignal } = {},
) {
  return fetchStream<ChatEvent>(
    (env.NEXT_PUBLIC_API_URL ?? "http://localhost:8000/api") + "/chat/stream",
    {
      body: JSON.stringify({
        messages: [userMessage],
        deep_thinking_mode: params.deepThinkingMode,
        search_before_planning: params.searchBeforePlanning,
        debug:
          location.search.includes("debug") &&
          !location.search.includes("debug=false"),
        team_members: params.teamMembers,
        session_id: params.sessionId,  // 传递sessionId给后端
        username: params.username,
        mode: params.mode || "search", // 默认使用搜索模式
      }),
      signal: options.abortSignal,
    },
  );
}

/**
 * 初始化聊天会话
 * @param message 初始消息内容
 * @returns 包含会话ID的响应
 */
export async function initiateChatSession(message: string) {
  try {
    // 获取当前认证信息
    const { auth } = useStore.getState();
    const username = auth.username || "anonymous";
    const response = await fetch(
      (env.NEXT_PUBLIC_API_URL ?? "http://localhost:8000/api") + "/chat/initiate",
      { 
        method: "POST",
        headers: {
          "Content-Type": "application/json"
        },
        body: JSON.stringify({
          message: message,
           username: username 
        }) 
      }
    );
    
    if (!response.ok) {
      throw new Error(`Failed to initiate chat session: ${response.status}`);
    }
    
    return await response.json() as { 
      session_id: string;
      initial_messages: any[];
      status: string;
    };
  } catch (error) {
    console.error("Error initiating chat session:", error);
    throw error;
  }
}

/**
 * 获取会话历史
 * @param sessionId 会话ID
 * @returns 会话历史记录
 */
export async function getSessionHistory(
  sessionId: string, 
  username: string
): Promise<SessionHistoryResponse> {
  try {
    const response = await fetch(`/api/session/${sessionId}/history`, {
      method: 'GET',
      headers: {
        'X-Username': username
      }
    });
    
    if (!response.ok) {
      if (response.status === 404) {
        // 会话不存在，清除本地存储的会话ID
        if (typeof window !== 'undefined') {
          localStorage.removeItem("deepmedical.session.id");
        }
        throw new Error('会话不存在或已删除');
      }
      throw new Error(`获取会话历史失败: ${response.statusText}`);
    }
    
    return await response.json() as SessionHistoryResponse;
  } catch (error) {
    console.error('获取会话历史失败:', error);
    throw error;
  }
}

// 获取用户会话列表
export async function fetchUserSessions(username: string): Promise<SessionListItem[]> {
  try {
    // 调试日志
    console.log('Fetching sessions for user:', username);
    
    const response = await fetch('/api/session/list', {
      method: 'GET',
      headers: {
        'X-Username': username
      }
    });
    
    // 调试日志：打印响应状态
    console.log('Session list response status:', response.status);
    
    if (!response.ok) {
      throw new Error(`获取会话列表失败: ${response.statusText}`);
    }
    
    const data = await response.json();
    
    // 调试日志：打印响应数据
    console.log('Session list data:', data);
    
    return data as SessionListItem[];
  } catch (error) {
    console.error('获取会话列表失败:', error);
    return [];
  }
}


export async function queryTeamMembers() {
  try {
    const response = await fetch(
      (env.NEXT_PUBLIC_API_URL ?? "http://localhost:8000/api") +
        "/team_members",
      { method: "GET" },
    );
    const { team_members } = (await response.json()) as {
      team_members: Record<string, TeamMember>;
    };
    const allTeamMembers = Object.values(team_members);
    return [
      ...allTeamMembers.filter((member) => !member.is_optional),
      ...allTeamMembers.filter((member) => member.is_optional),
    ];
  } catch (err) {
    console.warn(
      "🖐️️ [deepmedical]\n\nError connecting to deepmedical backend. Please ensure the latest version is running locally. See: https://github.com/deepmedical/deepmedical.\n\nRaw network error: ",
    );
    console.error(err);
    return [];
  }
}
